package meijuli.com.join51.business.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.jhx.common.http.ApiManager;
import com.jhx.common.http.HttpRequest;
import com.jhx.common.http.HttpResponse;
import com.jhx.common.http.ResponseCallback;
import com.jhx.common.utils.ToastUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.List;
import meijuli.com.join51.business.Confirm;
import meijuli.com.join51.business.R;
import meijuli.com.join51.business.activity.ChangeNameActivity;
import meijuli.com.join51.business.activity.MainActivity;
import meijuli.com.join51.business.activity.UserMessageActivity;
import meijuli.com.join51.business.adapter.UserMsgAdapter;
import meijuli.com.join51.business.aliyun.ImageUtils;
import meijuli.com.join51.business.model.EventBean;
import com.jhx.common.model.User;
import meijuli.com.join51.business.model.UserData;
import meijuli.com.join51.business.service.ApiService;
import meijuli.com.join51.business.utils.SoftInputUtil;
import com.jhx.common.utils.UserManager;
import retrofit2.Call;

/**
 * 商家信息页面
 *
 * @author wenqin 2017-04-14 17:31
 */
public class UserInfoFragment extends PhotoFragment implements ImageUtils.SelectImageListener {
    RecyclerView mReviewRv;
    SwipeRefreshLayout mSwipeRefreshLayout;
    TextView mDiscountTxt;
    TextView mTextView;
    private List<Confirm> mConfirmList;
    private UserMsgAdapter mAdapter;
    private Call<HttpResponse<UserData>> mCall;
    private Call<HttpResponse<String>> call;
    private User mUser;

    public static UserInfoFragment newInstance(User user) {
        Bundle args = new Bundle();
        args.putSerializable(MainActivity.KEY_USER, user);
        UserInfoFragment fragment = new UserInfoFragment();
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_user_message, container, false);
        EventBus.getDefault().register(this);
        mReviewRv = view.findViewById(R.id.review_rv);
        mSwipeRefreshLayout = view.findViewById(R.id.swipe_refresh_layout);
        mDiscountTxt = view.findViewById(R.id.txt_discount);
        mTextView = view.findViewById(R.id.txt_title);
        return view;
    }

    @SuppressLint("SetTextI18n")
    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (UserManager.get().checkUserNull(getActivity())) {
            return;
        }
        mUser = UserManager.get().getUser();
        if(!TextUtils.isEmpty(UserManager.get().getDiscount())){
            mDiscountTxt.setText(UserManager.get().getDiscount() + "%");
        } else {
            mTextView.setVisibility(View.GONE);
            mDiscountTxt.setVisibility(View.GONE);
        }
        mConfirmList = new ArrayList<>();

        mAdapter = new UserMsgAdapter(getActivity(), mConfirmList);
        mReviewRv.setLayoutManager(new LinearLayoutManager(getActivity()));
        mReviewRv.setNestedScrollingEnabled(false);
        mReviewRv.setAdapter(mAdapter);

        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                requestUserMsg();
            }
        });

        requestUserMsg();

        mAdapter.setOnItemClickListener(new UserMsgAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                switch (position) {
                    // 图片
                    case 0:
                        showListDialog();
                        break;
                    // 名字
                    case 1:
                        ChangeNameActivity.start(mActivity);
                        break;
                    default:

                        break;
                }
            }
        });

    }

    private void requestUserMsg() {
        if (!mSwipeRefreshLayout.isRefreshing()) {
            mSwipeRefreshLayout.setRefreshing(true);
        }
        mCall = ApiManager.get().getApiService(ApiService.class).getUserInfo();
        HttpRequest.getRequest().autoRecycle(this).start(mCall, new ResponseCallback<UserData>() {

            @Override
            public void onSuccess(String url, UserData data) {
                mUser = data.getUser();
                if (mUser != null) {
                    updateList(mUser);
                    UserManager.get().setUser(mUser);
                } else {
                    ToastUtil.getInstance().showToast("获取数据失败");
                }
                mSwipeRefreshLayout.setRefreshing(false);
                EventBus.getDefault().post(new EventBean<>(EventBean.STATUS_HOME_MSG));
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                mSwipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void updateList(User userInfo) {
        mConfirmList.clear();
        addConfirmContent(userInfo.getHeadImage(), "店铺头像");
        addConfirmContent(userInfo.getBusinessName(), "店铺名称");
        addConfirmContent(userInfo.getType() == User.TYPE_ONLINE ?
                "网店" : "实体店", "店铺类型");
        // 展示网店信息
        if (userInfo.getType() == User.TYPE_ONLINE) {
            addConfirmContent(userInfo.getLegal(), "法人姓名");
            addConfirmContent(userInfo.getIDCard(), "身份证号");
            addConfirmContent(userInfo.getLegalIDfront() +
                    "," + userInfo.getLegalIDback(), "身份证图片", false);
            addConfirmContent(userInfo.getCategoryName(), "行业分类");
            addConfirmContent(userInfo.getProvinceName() + " "
                    + userInfo.getCityName() + " " + userInfo.getTownName(), "商铺区域");
        } else {
            // 展示实体店信息
            addConfirmContent(userInfo.getRegisterNum(), "注册号");
            addConfirmContent(userInfo.getLicense(), "营业执照", false);
            addConfirmContent(userInfo.getLegal(), "法人姓名");
            addConfirmContent(userInfo.getIDCard(), "身份证号");
            addConfirmContent(userInfo.getLegalIDfront() +
                    "," + userInfo.getLegalIDback(), "身份证正反照", false);
            addConfirmContent(userInfo.getCategoryName(), "行业分类");
            addConfirmContent(userInfo.getProvinceName() + " "
                    + userInfo.getCityName() + " " + userInfo.getTownName(), "店铺区域");
            addConfirmContent(userInfo.getAddress() + userInfo.getShopAdd(), "店铺地址");
            addConfirmContent(userInfo.getShopPhoto(), "店铺环境照", false);
        }

        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            ((UserMessageActivity) mActivity).setToolBarTitle("商家信息");
            SoftInputUtil.get().hideSoftKeyboard(mActivity);
        }
    }


    @Override
    protected void onUpLoadSuccess(String cloudKey, String sourceFilePath) {
        uploadHeadIcon(cloudKey, sourceFilePath);
    }

    private void uploadHeadIcon(final String cloudKey, final String sourceFilePath) {
        call = ApiManager.get().getApiService(ApiService.class).uploadHeadIcon(cloudKey);
        HttpRequest.getRequest().autoRecycle(this).start(call, new ResponseCallback<String>() {

            @Override
            public void onSuccess(String url, String data) {
                dismissDialog();
                if (mUser == null) {
                    ToastUtil.getInstance().showToast("无法正确获取数据，上传图片失败，请退出重试");
                    return;
                }
                Confirm confirm = mConfirmList.get(0);
                confirm.setContent(sourceFilePath);
                mAdapter.notifyItemChanged(0);
                mUser.setHeadImage(data);
                UserManager.get().setUser(mUser);
                EventBus.getDefault().post(new EventBean<>(EventBean.STATUS_HOME_MSG));
            }

            @Override
            public void onError(String url, int errorCode, String errorMsg) {
                super.onError(url, errorCode, errorMsg);
                dismissDialog();
            }
        });
    }

    private void addConfirmContent(String content, String title, boolean isShowText) {
        Confirm confirm = new Confirm();
        confirm.setContent(content);
        confirm.setShowText(isShowText);
        confirm.setTitle(title);
        mConfirmList.add(confirm);
    }

    private void addConfirmContent(String content, String title) {
        addConfirmContent(content, title, true);
    }

    @Subscribe
    public void onEvent(EventBean bean) {
        switch (bean.getStatus()) {
            case EventBean.STATUS_MSG:
                requestUserMsg();
                break;
            default:

                break;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}
